<template>

<!--  <div>-->
<!--    <Slider :slider-data="noticeData" @getTitle="getSliderTitle"></Slider>-->
<!--  </div>-->


  <div class="app-container">


    <el-card>
      <Notice :lists="noticeData"></Notice>
    </el-card>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" style="margin-top: 20px">
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
          <el-option
            v-for="dict in order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单日期" prop="orderDate">

        <div class="block">
          <el-date-picker
              v-model="queryParams.orderDate"
              type="datetimerange"
              :shortcuts="shortcuts"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
          />
        </div>

      </el-form-item>
      <el-form-item label="业务类型" prop="businessType">
        <el-select v-model="queryParams.businessType" placeholder="请选择业务类型" clearable>
          <el-option
            v-for="dict in business_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="销售订单编号"  width="150px" align="center" prop="orderId" />
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>

      <el-table-column label="业务类型" align="center" prop="businessType">
        <template #default="scope">
          <dict-tag :options="business_type" :value="scope.row.businessType"/>
        </template>
      </el-table-column>
      <el-table-column v-if="customerOptions.length > 0" label="客户名称" align="center" width="150px">
        <template #default="scope">
          {{
            transformInfo(scope.row.customerId)
          }}
        </template>
      </el-table-column>
<!--      <el-table-column label="关联编号" align="center" prop="referenceId" />-->
<!--      <el-table-column label="付款方式" align="center" prop="paymentMethod">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="payment_meth" :value="scope.row.paymentMethod"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="订单总价" align="center" prop="orderTotal" width="140">
        <template #default="scope">
          <span>￥{{scope.row.orderTotal}}</span>
        </template>
      </el-table-column>>
      <el-table-column label="发票信息" align="center" prop="invoiceInfo" >
        <template #default="scope">
          <image-preview :src="scope.row.invoiceInfo" />
        </template>
      </el-table-column>
      <el-table-column label="订单日期" align="center" prop="orderDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改日期" align="center" prop="modifiedDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.modifiedDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改日期" align="center" prop="lastModifiedDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.modifiedDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" prop="lastModifiedBy" />
      <el-table-column label="备注" align="center" prop="note" width="200"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:order:edit']" v-show="scope.row.orderStatus==='2'">修改</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:order:edit']" v-show="scope.row.orderStatus==='4'">变更</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:order:edit']" v-show="scope.row.orderStatus==='1'">审核</el-button>
          <el-button link type="primary" icon="View" @click="handleDetails(scope.$index, scope.row)"
                     v-hasPermi="['system:order:edit']">查看详情</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:order:remove']"  v-show="scope.row.orderStatus==='9'">删除</el-button>


        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />



  </div>



</template>

<script setup name="Order">
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  getOrderCount,
  getCustomerStatusCount
} from "@/api/system/order.js";
import {getCustomerList, getInfo, listInfo} from "@/api/system/info.js";
import {getUserProfile} from "@/api/system/user.js";
import useUserStore from '@/store/modules/user';
import Notice from "@/views/order/components/Notice.vue";
import {listMessage , updateMessage} from "@/api/system/message.js";
import ImagePreview from "@/components/ImagePreview/index.vue";
const { proxy } = getCurrentInstance();
const { payment_meth, order_status, business_type } = proxy.useDict('payment_meth', 'order_status', 'business_type');

const useStore = useUserStore()
const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const messagetotal = ref(0);
const title = ref("");
const customerOptions = ref([]);
const fetchCustomerList = () => {
  return new Promise((resolve) => {
    getCustomerList().then(response => {
      customerOptions.value = response.rows;
      console.log("customerOptions:", customerOptions.value);
      resolve();
    }).catch(error => {
      console.error('获取客户列表失败:', error);
      resolve(); // 即使失败也继续流程
    });
  });
};

const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
]

const noticeData = ref([]);

const data = reactive({
  form: {},

  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderStatus: null,
    orderDate: null,
    businessType: null,
    customerId: null,
    referenceId: null,
  },
  customerOptions:[],

});


const { queryParams, cqueryParams,form, rules } = toRefs(data);



function readMessage(){

  obj.value.forEach(item => {


    if (item.status === 0) {
      item.status = 1;
      const processData ={
        messageId: item.messageId,
        userId :item.userId,
        status: 1,
      }

      updateMessage(processData).then(response => {

      })
    }

  })
  drawerStore.closeDrawer();

}

function transformInfo(customerId){
  const customer = customerOptions.value.find(c =>
      c.customerId == customerId // 使用==解决类型不一致问题
  );
  return customer?.customerName || customerId; // 确保有返回值
}


/** 查询订单管理列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    orderList.value.sort((a, b) => {

      const dateA = new Date(a.orderDate);
      const dateB = new Date(b.orderDate);
      return dateB - dateA;

    });
    console.log('sort',orderList.value)
    total.value = response.total;
    loading.value = false;

   /* orderList.value.forEach(item => {
      if(item.orderStatus==='1'){
        item.orderStatus='待确认';
      }else if(item.orderStatus==='2'){
        item.orderStatus='待支付';
      }else if(item.orderStatus==='3'){
        item.orderStatus='已支付';
      }else if(item.orderStatus==='4'){
        item.orderStatus='待发货';
      }else if(item.orderStatus==='5'){
        item.orderStatus='运输中';
      }
    })*/

  });
}

function getCustomerOrderList(){
  loading.value = true;
  queryParams.value = {
    pageNum: 1,
        pageSize: 10,
        orderStatus: null,
        orderDate: null,
        businessType: null,
        customerId: useStore.id,
        referenceId: null,
  },
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    orderList.value.sort((a, b) => {

      const dateA = new Date(a.orderDate);
      const dateB = new Date(b.orderDate);
      return dateB - dateA;

    });
    console.log('sort',orderList.value)
    total.value = response.total;
    loading.value = false;


  });
}

function getCustomerCount(){

  getCustomerStatusCount(useStore.id).then(response => {

    console.log('成功调用getCustomerCount',response.data)

  const orderCount = response.data;

  let days = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];

  let now = new Date();

    noticeData.value = [
      '温馨提示: ',
      `今天是 ${now.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })} ${days[now.getDay()]}`,
      '今日待办事项：'
    ];

  console.log(response.data)

  console.log(orderCount)

  orderCount.forEach(item => {
    if(item.orderStatus==='1'){
      item.orderStatus='待确认';
      noticeData.value.push(item.orderStatus+ '（'+item.orderCount+'）')
    }else if(item.orderStatus==='2'){
      item.orderStatus='待支付';
      noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
    }else if(item.orderStatus==='3'){
      item.orderStatus='已支付';
      noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
    }else if(item.orderStatus==='4'){
      item.orderStatus='待发货';
      noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
    }else if(item.orderStatus==='5'){
      item.orderStatus='运输中';
      noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
    }else if(item.orderStatus==='6'){
      item.orderStatus='派送中';
      noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
    }else if(item.orderStatus==='7'){
      item.orderStatus='待签收';
      noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
    }else if(item.orderStatus==='8'){
      item.orderStatus='已签收';
    }
  })

    console.log('orderCount:', orderCount)

    console.log('noticeData:', noticeData.value)

  });
}

function getCount(){

  getOrderCount().then(response => {

    const orderCount = response.data;

    let days = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];

    let now = new Date();

    noticeData.value = [
      '温馨提示: ',
      `今天是 ${now.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })} ${days[now.getDay()]}`,
      '今日待办事项：'
    ];

    console.log(response.data)

    console.log(orderCount)

    orderCount.forEach(item => {
      if(item.orderStatus==='1'){
        item.orderStatus='待确认';
        noticeData.value.push(item.orderStatus+ '（'+item.orderCount+'）')
      }else if(item.orderStatus==='2'){
        item.orderStatus='待支付';
        noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
      }else if(item.orderStatus==='3'){
        item.orderStatus='已支付';
        noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
      }else if(item.orderStatus==='4'){
        item.orderStatus='待发货';
        noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
      }else if(item.orderStatus==='5'){
        item.orderStatus='运输中';
        noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
      }else if(item.orderStatus==='6'){
        item.orderStatus='派送中';
        noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
      }else if(item.orderStatus==='7'){
        item.orderStatus='待签收';
        noticeData.value.push(item.orderStatus+'（'+item.orderCount+'）')
      }else if(item.orderStatus==='8'){
        item.orderStatus='已签收';
      }
    })

    console.log('orderCount:', orderCount)

    console.log('noticeData:', noticeData.value)

  });
}


function getSliderTitle (title) { // 获取点击的标题
  console.log('title:', title)
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    orderId: null,
    orderStatus: null,
    orderDate: null,
    modifiedDate: null,
    businessType: null,
    customerId: null,
    referenceId: null,
    paymentMethod: null,
    orderTotal: null,
    invoiceInfo: null,
    lastModifiedDate: null,
    lastModifiedBy: null,
    note: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {

  if (queryParams.value.orderDate && queryParams.value.orderDate.length === 2) {
    const [startDate, endDate] = queryParams.value.orderDate.map(date => date.toISOString());
    queryParams.value.orderDate = `${startDate},${endDate}`;
  }
  console.log('queryParams',queryParams.value.orderDate)
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}



function handleDetails(index,row){
    proxy.$router.push({path:'/orderDetails/orderDetails',query:{id:row.orderId}})
}



// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.orderId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
    proxy.$router.push({path:'/orderadd/orderadd'})
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
    proxy.$router.push({path:'/orderEdit/orderEdit',query:{id:row.orderId}})
  // const _orderId = row.orderId || ids.value
  // getOrder(_orderId).then(response => {
  //   form.value = response.data;
  //   open.value = true;
  //   title.value = "修改订单管理";
  // });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.orderId != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _orderIds = row.orderId || ids.value;
  proxy.$modal.confirm('是否确认删除订单管理编号为"' + _orderIds + '"的数据项？').then(function() {
    return delOrder(_orderIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

async function getUserInfo() {
  try {
    const response = await getUserProfile();
    console.log('userinfo response:', response.data.roles[0].roleName);
    return response.data.roles[0].roleName;
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
}

onMounted(async () => {

  const role = await getUserInfo();
  await fetchCustomerList()

  if (role === '平台运营商' || role === '超级管理员') {

    getList();
    getCount();
  } else {
    getCustomerOrderList();

    getCustomerCount();
  }

});

</script>
<style scoped>

.el-drawer {
  margin-top: 50px;
}
/* 设置弹层标题和内容的间隔 */
.el-drawer__header {
  margin: 0 !important;
}

/* 内容 */
.msgContent {
  margin-right: 5%;
  margin-top: 10px;
  font-size: 13px;
  white-space: normal;
  line-height: 1.5;
}

/* 标题 */
.msgTitle {
  font-size: 15px;
  font-weight: bold;
  cursor: pointer;

}

/* 时间 */
.msgTime {
  font-size: 14px;
  height: 20px;
  color: #d0cbcb;
  float: right;
  margin-right: 5%;
}
.action-button {
  position: absolute;
  right: 10px;
}
.button{
  position: absolute;
  right: 40px;
  top: 80px
}

</style>